package com.ksvip.next.components.groovy.autoconfigure;

import java.io.FilenameFilter;

import com.ksvip.next.components.groovy.properties.GroovyClasspathLoaderProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ksvip.next.components.groovy.annotation.condition.ConditionalOnExistingProperty;
import com.ksvip.next.components.groovy.compiler.DynamicCodeCompiler;
import com.ksvip.next.components.groovy.filter.GroovyFileNameFilter;
import com.ksvip.next.components.groovy.loader.ClasspathScriptLoader;


/**
 * <p>
 * 从classpath下加载groovy脚本的loader自动配置类 配置里必须要显示开启该加载器时才注入
 * {@code enhance.groovy.engine.classpath-loader.enable}
 * </p>
 *
 * @author wenpan 2022/09/25 15:23
 */
@Configuration
@EnableConfigurationProperties(value = {GroovyClasspathLoaderProperties.class})
@ConditionalOnExistingProperty(property = GroovyClasspathLoaderProperties.PREFIX + ".enable", value = "true")
public class GroovyClasspathLoaderAutoConfiguration {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * <p>
     * 注册基于 classpath 的ScriptLoader
     * </p>
     */
    @Bean(value = "classpathScriptLoader")
    @ConditionalOnMissingBean(ClasspathScriptLoader.class)
    public ClasspathScriptLoader classpathScriptLoader(DynamicCodeCompiler dynamicCodeCompiler,
                                                       GroovyClasspathLoaderProperties classpathLoaderProperties) {
        this.logger.info("loading ScriptLoader type is [{}]", ClasspathScriptLoader.class);
        return new ClasspathScriptLoader(dynamicCodeCompiler, classpathLoaderProperties, this.groovyFileNameFilter());
    }

    /**
     * 文件名称过滤器
     */
    @Bean
    public FilenameFilter groovyFileNameFilter() {

        return new GroovyFileNameFilter();
    }
}
